using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

using System.Threading;

using Microsoft.PowerShell.CmdletManagement;

namespace Microsoft.PowerShell.CmdletManagement
{
    /// <summary>
    /// Interaction logic for SelectProject.xaml
    /// </summary>

    public partial class SelectProject : System.Windows.Window
    {
        public SelectProject(string serviceUri, Window owner)
        {
            InitializeComponent();

            this._serviceUri = new Uri(serviceUri);
            this.Projects.Focus();
            this.Owner = owner;

            Thread t = new Thread(new ThreadStart(GetProjects));
            t.IsBackground = true;
            t.Start();
        }

        private readonly Uri _serviceUri;
        private List<PsSpecProject> projects;

        delegate void UpdateProjectsDelegate();

        private void GetProjects()
        {
            GetPsSpecProjectCommand command = new GetPsSpecProjectCommand();
            command.ServiceUri = _serviceUri;

            List<PsSpecProject> results = new List<PsSpecProject>();
            System.Collections.IEnumerable pipelineResults = new Object[0];
            pipelineResults = command.Invoke();

            try
            {
                foreach (PsSpecProject result in pipelineResults)
                {
                    results.Add(result);
                }
            }
            catch (Exception exception)
            {
                CmdletDesignerUtils.HandleException("Error loading projects",
                    "There were errors loading the list of projects.",
                    exception);
            }

            projects = results;

            Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new UpdateProjectsDelegate(UpdateProjects));
        }

        private void UpdateProjects()
        {
            this.Projects.DataContext = projects;
            ProgressIndicator.Visibility = Visibility.Hidden;
        }

        private void DoubleClick_SelectProject(Object sender, MouseButtonEventArgs e)
        {
            SelectProjectAndExit();
        }

        private void Click_SelectProject(Object sender, RoutedEventArgs e)
        {
            SelectProjectAndExit();
        }

        private void SelectProjectAndExit()
        {
            if (this.Projects.SelectedItems.Count > 0)
            {
                Application.Current.Properties["SelectedProject"] = this.Projects.SelectedItem;
                this.DialogResult = true;
                this.Close();
            }
        }
    }
}